# =RJabberD - Jabber Server for Ruby
# License:: Ruby's license (see LICENSE file), GNU GPL or GNU LGPL at your option.
# Website:: http://code.google.com/p/rjabberd

require 'strscan'

module RJabberD
  module XML

    # =Sanitize - Removes illegal XML 1.0 characters from a string.
    def XML.sanitize(text)
      result = ""
      scanner, char = StringScanner.new(text), /./mu

      while true
        break unless c = scanner.scan(char)
        unicode = c.unpack("U")[0]

        result << c if
          unicode == 0x9 ||
          unicode == 0xA ||
          unicode.between?( 0x20, 0xD7FF ) ||
          unicode.between?( 0xE000, 0xFFFD ) ||
          unicode.between?( 0x10000, 0x10FFFF)
      end

      return result
    end
  end
end
